package cn.zhqr.lib.utils;


import cn.zhqr.common.util.str.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by charles on 2017/12/15.
 */
public class FileUtils {
    public static String getSuffix(String filename){
        if(StringUtils.isBlank(filename) || !filename.contains(".")){
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }



    public static boolean fileExist(String outDir) {
        return new File(outDir).exists();
    }
    public static boolean fileNotExist(String outDir) {
        return !fileExist(outDir);
    }

    public static File createZip(List<File> files,String zipname) throws IOException {
        File zipFile = new File(zipname);
        OutputStream os = new BufferedOutputStream( new FileOutputStream( zipFile ) );
        ZipOutputStream zos = new ZipOutputStream( os );
        byte[] buf = new byte[8192];
        int len;
        for (int i=0;i<files.size();i++) {
            File file = files.get(i);
            if ( !file.isFile() ) continue;
            ZipEntry ze = new ZipEntry( file.getName() );
            zos.putNextEntry( ze );
            BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
            while ( ( len = bis.read( buf ) ) > 0 ) {
                zos.write( buf, 0, len );
            }
            zos.closeEntry();
        }
        //zos.setEncoding("GBK");
        zos.closeEntry();
        zos.close();

        if(zipFile.exists()){
            return zipFile;
        }
        return null;
    }

    public static boolean mkdirIfNotExits(String outDir) {
        File file = new File(outDir);
        if(!file.exists()){
            file.mkdirs();
        }
        return file.exists();
    }

    public static double getFileSize(File file, Unit unit){
        long len = file.length();
        double fileSize = 0;
        if (unit==Unit.B) {
            fileSize = (double) len;
        } else if (unit==Unit.KB) {
            fileSize = (double) len / 1024;
        } else if (unit==Unit.MB) {
            fileSize = (double) len / 1048576;
        } else if (unit==Unit.GB) {
            fileSize = (double) len / 1073741824;
        }
        return fileSize;
    }

    public enum Unit{
        B,KB,MB,GB,TB
    }


    /**
     * 指定图片宽度和高度和压缩比例对图片进行压缩
     *
     * @param imgsrc
     *            源图片地址
     * @param imgdist
     *            目标图片地址
     * @param max_widthdist
     *            图片的最大宽度，超过则按比例缩放
     */
    public static void compressImg(String imgsrc, String imgdist, int max_widthdist) {
        try {
            File srcfile = new File(imgsrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            // 如果比例不为空则说明是按比例压缩
            //获得源图片的宽高存入数组中
            int[] results = getImgWidthHeight(srcfile);
            if (results == null || results[0] == 0 || results[1] == 0) {
                return;
            }
            int widthdist = results[0];
            int heightdist = results[1];

            if(max_widthdist>0 && widthdist>max_widthdist){
                //按比例缩放或扩大图片大小，将浮点型转为整型
                heightdist = (int) ((1.0*max_widthdist/widthdist)*results[1]);
                widthdist = max_widthdist;
            }

            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage(widthdist, heightdist, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本，返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

//            //创建文件输出流
            FileOutputStream out = new FileOutputStream(imgdist);
//            //将图片按JPEG压缩，保存到out中
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(tag);
            ImageIO.write(tag, "jpeg", out);
            //关闭文件输出流
            out.close();
        } catch (Exception ef) {
            ef.printStackTrace();
        }
    }

    /**
     * 获取图片宽度和高度
     *
     * @return 返回图片的宽度
     */
    public static int[] getImgWidthHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = { 0, 0 };
        try {
            // 获得文件输入流
            is = new FileInputStream(file);
            // 从流里将图片写入缓冲图片区
            src = ImageIO.read(is);
            result[0] =src.getWidth(null); // 得到源图片宽
            result[1] =src.getHeight(null);// 得到源图片高
            is.close();  //关闭输入流
        } catch (Exception ef) {
            ef.printStackTrace();
        }

        return result;
    }
}
